package cn.derry.servlet;

import cn.derry.domain.Account;
import org.omg.PortableInterceptor.USER_EXCEPTION;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author MangoDai
 * @decription 登录
 * @date 2017/12/20
 **/
public class LoginServlet extends HttpServlet {
    private static HashMap<String, Account> accounts = new LinkedHashMap<String, Account>();
    public static final String SESSION_USER = "SESSION_USER";

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String filePath = config.getInitParameter("accounts");
        if (accounts != null) {
            InputStream stream = getClass().getClassLoader().getResourceAsStream(filePath);
            try {
                BufferedReader bis = new BufferedReader(new InputStreamReader(stream, "utf-8"));
                String line = null;
                while ((line = bis.readLine()) != null) {
                    getAccount(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("账户初始化成功 length : " + accounts.size());
            config.getServletContext().setAttribute("accounts", accounts);
        } else {
            System.out.println("账户初始化失败 ");
            destroy();
        }
    }

    private void getAccount(String line) {
        String[] split = line.split(" ");
        if (split.length == 6) {
            Account account = new Account(split[0], split[1], split[2], split[3], split[4], split[5].substring(12));
            accounts.put(account.getId(), account);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/fail.jsp");
    }

    private Account isAuthenticate(String id, String password) {
        if (null != accounts && accounts.containsKey(id)) {
            Account account = accounts.get(id);
            if (account.getPassword().equals(password.toLowerCase())) {
                return account;
            }
        }
        return null;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        Account authenticate = isAuthenticate(id, password);
        if (authenticate == null) {
            if (addLoginTimes(req, id)) {
                req.setAttribute("msg", "你的账户或者密码错误,请输入你的学号和身份证后6位");
            } else {
                req.setAttribute("msg", "别想暴利破解，不存在的。");
            }
            req.getRequestDispatcher("/fail.jsp").forward(req, resp);
        }
        req.getSession(true).setAttribute(SESSION_USER, authenticate);
        req.getRequestDispatcher("/chat/chating.jsp").forward(req, resp);
    }

    private boolean addLoginTimes(HttpServletRequest req, String id) {
        HttpSession session = req.getSession(true);
        String sessionLoginKey = getSessionLoginKey(id);
        Integer flag = (Integer) session.getAttribute(sessionLoginKey);
        if (flag != null && flag < 6) {
            session.setAttribute(sessionLoginKey, new AtomicInteger(flag).incrementAndGet());
            return true;
        } else {
            return false;
        }
    }

    private String getSessionLoginKey(String id) {
        return id + "LOGIN_TIME";
    }
}
